﻿@using Contrib.Taxonomies.Models;
@using Contrib.Taxonomies.Helpers;
@using PmpNetwork.Extensions;
@{
    Script.Require("jQuery").AtHead();
    Script.Require("PmpNetwork.JsTree");
    
    int level=0;
    int firstLevel = -1;

    var currentSlug = String.Empty;
    var routeDataValues = ViewContext.RouteData.Values;
    
    if (routeDataValues.ContainsKey("controller") 
        && String.Compare((string)routeDataValues["controller"], "wiki", true) == 0
        && routeDataValues.ContainsKey("name")) {
            currentSlug = ((string)routeDataValues["name"]).ToLower();
    }
}

<div class="category-tree">
<ul class="terms">
	@foreach (TermPart term in Model.Terms) {
        var friendlyName = term.Name.ToLowerInvariant().Replace(' ', '-');
        var isCurrent = !String.IsNullOrEmpty(currentSlug) && String.Compare(friendlyName, currentSlug, true) == 0;
        
         if(firstLevel == -1){
             firstLevel = term.GetLevels();
         }
		if(term.GetLevels() - firstLevel > level) {
			level++;
			@:<ul class="terms">
		}
		    @:</li>
		
		while(term.GetLevels() - firstLevel < level) {
			level--;
			@:</ul>
		}

		@:<li @(isCurrent ? "id=selected-node" : "")>
			<a href="@Url.WikiUrl(term.Name)" id="@friendlyName">@term.Name</a>
    }
        
		</li>
	@for (int i = 0; i < level; i++)
 {
	@:</ul>
	}
</ul>
</div>
<script type="text/javascript">
    (function ($, undefined) {
        $(document).ready(function () {
            var initialOpen = [];
            if ($("#selected-node").length > 0) {
                initialOpen.push("selected-node");
                var openIndex = 0;
                $("#selected-node").parents("li").each(function () {
                    var id = 'selected-node-' + openIndex;
                    $(this).attr("id", id);
                    initialOpen.push(id);
                });
            }
            $(".category-tree").jstree({
                "plugins": ["themes", "html_data"],
                "core": { "initially_open": initialOpen }
            });
        });
    })(jQuery);
</script>